package com.twang.stock.ebay;

import com.twang.stock.entity.AmazonMerchantInfo;
import com.twang.stock.mapper.AmazonMerchantInfoMapper;
import com.twang.stock.redis.RedisUtil;
import com.twang.stock.rocketMq.RocketMQProducer;
import com.twang.stock.threadPool.AsycTaskExecutorConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.assertj.core.util.Lists;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.regex.Pattern;

@Slf4j
@Service
public class AmazonService {

    private static  String key_="ebay:EbaySearchByTypeService:";

    private static final Pattern PATTERN = Pattern.compile("/(sch|str)/([^/?]+)");


    @Autowired
    private static RedisUtil redisUtil;
    @Autowired
    private RocketMQProducer rocketMQProducer;

    @Resource
    private AmazonMerchantInfoMapper amazonMerchantInfoMapper;

    @Resource
    private AsycTaskExecutorConfig asycTaskExecutorConfig;


    public List getList(){
       List<String> list = amazonMerchantInfoMapper.getQueryTypeList();
       return list;
    }

    public List getDetailList(String name){
        AmazonMerchantInfo param=new AmazonMerchantInfo();
        param.setName(name);
        List<AmazonMerchantInfo> list = amazonMerchantInfoMapper.selectByName(param);
        return list;
    }

    public  void getAmazonPage(String url,int page,String name) {
        // 目标URL（包含搜索参数）
         url = url+"&ref=sr_pg_"+page;
        log.info(">>>>>{} 执行第{} 页",name,page);
        try (CloseableHttpClient httpClient = HttpClients.createDefault()) {
            // 创建GET请求
            HttpGet httpGet = new HttpGet(url);

            // 设置请求头（模拟浏览器访问）
            httpGet.setHeader("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36");
            httpGet.setHeader("Accept-Language", "zh-CN,zh;q=0.9,en;q=0.8");
            httpGet.setHeader("Accept-Encoding", "gzip, deflate, br, zstd");
            httpGet.setHeader("Referer", "https://www.amazon.com/-/zh/ref=nav_logo");
            httpGet.setHeader("Cookie", "session-id=130-8138511-6012064; ..."); // 完整cookie见原始请求头

            // 发送请求并获取响应
            try (CloseableHttpResponse response = httpClient.execute(httpGet)) {
                // 处理响应
                if (response.getStatusLine().getStatusCode() == 200) {
                    String htmlContent = EntityUtils.toString(response.getEntity());
                    // 网页内容解析
                    Document doc = Jsoup.parse(htmlContent);
                    // 获取所有 div 元素
                    Elements divs = doc.select("div.sg-col-inner");
                    CountDownLatch countDownLatch = new CountDownLatch(divs.size());
                    // 遍历每个 div 元素
                    int j = 1;
                    List<AmazonMerchantInfo> amazonMerchantInfoList=Lists.newArrayList();
                    for (Element div : divs) {
                        if (j < 4) {
                            j++;
                            countDownLatch.countDown();
                            continue;
                        }
//                        asycTaskExecutorConfig.taskQueueExecutor().execute(() -> {
                            try {
                                AmazonMerchantInfo amazonMerchantInfo=new AmazonMerchantInfo();

                                //评论数
                                try {
                                    String coments = Jsoup.parse(div.toString()).select("span.a-size-base.s-underline-text[aria-hidden=true]").first().text().trim();
                                    coments = coments.replace(",", "");
                                    amazonMerchantInfo.setScore(Integer.valueOf(coments));
                                }catch (Exception e) {
                                    amazonMerchantInfo.setScore(-1);
                                }
                                //name
                                String detail = Jsoup.parse(div.toString()).select("a.a-link-normal.s-no-outline[href]").first().attr("href");
                                amazonMerchantInfo.setHomePage("https://www.amazon.com"+detail);

                                //name
                                amazonMerchantInfo.setName(name);

                                //HomePageName
                                Elements productNames = Jsoup.parse(div.toString()).select("h2.a-size-base-plus.a-spacing-none.a-color-base.a-text-normal span");
                                for (Element names : productNames) {
                                    amazonMerchantInfo.setHomePageName(names.text());
                                }

                                //购买数量
                                try{
                                    String purchaseCounts = Jsoup.parse(div.toString()).select("div.a-section.a-spacing-small.puis-padding-left-small.puis-padding-right-small > div[data-cy='reviews-block'] > div.a-row.a-size-base > span.a-size-base.a-color-secondary").first().text();
                                    if (StringUtils.isNotBlank(purchaseCounts)) {
                                        amazonMerchantInfo.setSoldGoods(purchaseCounts);
                                    }
                                }catch (Exception e){

                                }
                                if(StringUtils.isBlank(amazonMerchantInfo.getSoldGoods())){
                                    amazonMerchantInfo.setSoldGoods("---");
                                }

                                //
                                amazonMerchantInfoList.add(amazonMerchantInfo);
                            } catch (Exception e) {
                                log.error(">>>>>>>> Exception itemUserHomePage ", e);
                            } finally {
                                countDownLatch.countDown();
                            }

                       // });
                    }
                   // countDownLatch.await();
                    int num= amazonMerchantInfoMapper.batchInsert(amazonMerchantInfoList);
                    log.info(">>>>>name 执行完成，总共生成{} 条",num);
                } else {
                    System.out.println("请求失败，状态码：" + response.getStatusLine().getStatusCode());
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    public static void main(String[] args) {
        String url = "https://www.amazon.com/s?k=shoes&crid=F1AGJUH5GF10&sprefix=shoes%2Caps%2C408&ref=nb_sb_noss_1";
        //String response = getamazonPage(url);
        //System.out.println("Response Content: " + response);
    }
}
